from uuid import UUID
from fastapi import HTTPException
from sqlalchemy.ext.asyncio import AsyncSession

from crud import relation as relation_crud
from schemas.relation import RiskGuaranteeRelationCreate, RiskGuaranteeRelationResponse
from log import log_error

async def create_risk_guarantee_relation(
    db: AsyncSession,
    relation_data: RiskGuaranteeRelationCreate
) -> RiskGuaranteeRelationResponse:
    """创建风险与保障关联的业务逻辑"""
    try:
        db_relation = await relation_crud.create_relation(db, relation_data)
        return RiskGuaranteeRelationResponse.model_validate(db_relation)
    except Exception as e:
        log_error(f"Error creating relation: {str(e)}")
        raise HTTPException(status_code=400, detail="无法创建关联关系")

async def update_risk_guarantee_relation(
    db: AsyncSession,
    relation_id: UUID,
    relation_data: RiskGuaranteeRelationCreate
) -> RiskGuaranteeRelationResponse | None:
    """更新风险与保障关联的业务逻辑"""
    try:
        db_relation = await relation_crud.update_relation(
            db=db,
            relation_id=relation_id,
            relation_update=relation_data
        )
        if db_relation is None:
            return None
        return RiskGuaranteeRelationResponse.model_validate(db_relation)
    except Exception as e:
        log_error(f"Error updating relation {relation_id}: {str(e)}")
        raise HTTPException(status_code=400, detail="无法更新关联关系")

async def get_risk_guarantee_relation(
    db: AsyncSession,
    relation_id: UUID
) -> RiskGuaranteeRelationResponse:
    """获取指定ID的关联关系的业务逻辑"""
    db_relation = await relation_crud.get_relation(db, relation_id)
    if not db_relation:
        raise HTTPException(status_code=404, detail="未找到指定的关联关系")
    return RiskGuaranteeRelationResponse.model_validate(db_relation)

async def get_relations_for_risk(
    db: AsyncSession,
    risk_item_id: UUID
) -> list[RiskGuaranteeRelationResponse]:
    """获取指定风险项的所有关联关系的业务逻辑"""
    relations = await relation_crud.get_relations_by_risk(db, risk_item_id)
    return [RiskGuaranteeRelationResponse.model_validate(r) for r in relations]

async def delete_risk_guarantee_relation(
    db: AsyncSession,
    relation_id: UUID
) -> bool:
    """删除指定ID的关联关系的业务逻辑"""
    if not await relation_crud.delete_relation(db, relation_id):
        raise HTTPException(status_code=404, detail="未找到指定的关联关系")
    return True 